﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using Tickz.Commonz;
using System.IO;
namespace Tickz.Webz
{
    public class WebToolz
    {
        #region 反编码url
        /// <summary>
        /// 反编码url
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string DecodeUrl(string input)
        {
            return HttpUtility.UrlDecode(input);
        }
        /// <summary>
        /// 反编码url 指定编码
        /// </summary>
        /// <param name="input"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public  static  string DecodeUrl(string input,Encoding encode)
        {
            return HttpUtility.UrlDecode(input,encode);
        }
        #endregion

        #region 编码url
        /// <summary>
        /// 编码url
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string EncodeUrl(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return "";
            }
            return HttpUtility.UrlEncode(input).Replace("+","%20");
        }
        /// <summary>
        /// 编码url 指定编码
        /// </summary>
        /// <param name="input"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string EncodeUrl(string input,Encoding encode)
        {
            if (string.IsNullOrEmpty(input))
            {
                return "";
            }
            return HttpUtility.UrlEncode(input, encode).Replace("+", "%20");
        }
        #endregion

        #region 反格式化html标签
        /// <summary>
        /// 反格式化html标签
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string DecodeHtml(string strHtml)
        {
            return HttpUtility.HtmlDecode(strHtml);
            //strHtml = strHtml.Replace("<br>", "\n");
            //strHtml = strHtml.Replace("&gt;", ">");
            //strHtml = strHtml.Replace("&lt;", "<");
            //strHtml = strHtml.Replace("&nbsp;", " ");
            //strHtml = strHtml.Replace("&quot;", "\"");
            //return strHtml;
        }
        /// <summary>
        /// 反格式化 html标签 输出到Writer里
        /// </summary>
        /// <param name="strHtml"></param>
        /// <param name="outPut"></param>
        public  static  void DecodeHtml(string strHtml,TextWriter outPut)
        {
            HttpUtility.HtmlDecode(strHtml,outPut);
        }
        #endregion

        #region 格式化html标签
        /// <summary>
        /// 格式化html标签
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string EncodeHtml(string strHtml)
        {
            if (!string.IsNullOrEmpty(strHtml))
            {
                return HttpUtility.HtmlEncode(strHtml);
            }
            return "";
            //strHtml = strHtml.Replace("\"", "&quot;");
            //strHtml = strHtml.Replace("  ", " &nbsp;");
            //strHtml = strHtml.Replace("<", "&lt;");
            //strHtml = strHtml.Replace(">", "&gt;");
            //strHtml = strHtml.Replace("\n", "<br>");
            //return strHtml;
        }
        /// <summary>
        /// 格式化html标签
        /// </summary>
        /// <param name="strHtml"></param>
        /// <param name="outPut"></param>
        public  static  void EncodeHtml(string strHtml,TextWriter outPut)
        {
            if (!string.IsNullOrEmpty(strHtml))
            {
                 HttpUtility.HtmlEncode(strHtml,outPut);
            }
        }
        #endregion

        #region 过滤sql关键词，防止注入
        /// <summary>
        /// 过滤sql关键词，防止注入
        /// </summary>
        /// <param name="sqlStr"></param>
        /// <returns></returns>
        public static string SqlFiltrate(string sqlStr)
        {
            return Regex.Replace(sqlStr, @"\b(Insert|Delete|Update|Create|Drop|Exec|Dri)\b", "", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 取出文本中的图片地址
        ///   <summary> 
        ///   取出文本中的图片地址 
        ///   </summary> 
        ///   <param   name="htmlStr">HTMLStr</param> 
        public static string GetImgUrl(string htmlStr)
        {
            string str = string.Empty;
            //  string sPattern = @"^<img\s+[^>]*>";
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*(['""]?)(?<url>\S*)['""][^>]*?>",
              RegexOptions.Compiled);
            Match m = r.Match(htmlStr.ToLower());
            if (m.Success)
                str = m.Result("${url}");
            return str;
        }
        #endregion

        #region 去除HTML标记
        ///   <summary> 
        ///   过滤HTML
        ///   </summary> 
        public static string NoHtml(string htmlstring)
        {
            //删除脚本 
            htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "",
              RegexOptions.IgnoreCase);
            //删除HTML 
            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "",
              RegexOptions.IgnoreCase);
            //删除注释
            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            //转义字符
            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", "   ",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9",
              RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "",
              RegexOptions.IgnoreCase);

            //htmlstring=htmlstring.Replace("<", "");
            //htmlstring=htmlstring.Replace(">", "");
            //htmlstring=htmlstring.Replace("\r\n", "");
            //彻底过滤html
            htmlstring = HttpUtility.HtmlEncode(htmlstring);
            return htmlstring;
        }
        /// <summary>
        /// 过滤html
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string StripHtml(string strHtml)
        {
            string[] aryReg = 
            { 
              @"<script[^>]*?>.*?</script>", 
              @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\['tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", @"([\r\n])[\s]+",  
                @"&(quot|#34);", 
                @"&(amp|#38);", 
                @"&(lt|#60);", 
                @"&(gt|#62);",  
                @"&(nbsp|#160);", 
                @"&(iexcl|#161);", 
                @"&(cent|#162);", 
                @"&(pound|#163);", 
                @"&(copy|#169);", 
                @"&#(\d+);", 
                @"-->", 
                @"<!--.*\n" 
            };

            string[] aryRep = 
            { 
              "", 
              "", 
              "", 
              "\"", 
              "&", 
              "<", 
              ">", 
              "   ", 
              "\xa1",  //chr(161), 
              "\xa2",  //chr(162), 
              "\xa3",  //chr(163), 
              "\xa9",  //chr(169), 
              "", 
              "\r\n", 
              "" 
            };

            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }
            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");
            return strOutput;
        }
        ///   <summary> 
        ///   最简单的移除HTML标签 
        ///   </summary> 
        ///   <param   name="htmlStr">HTMLStr</param> 
        public static string ParseTags(string htmlStr)
        {
            return System.Text.RegularExpressions.Regex.Replace(htmlStr, "<[^>]*>", "");
        }
        #endregion
        #region js 提示信息
            public static void ShowOpen(string msg, string uri, string openType)
            {
                
                HttpContext.Current.Response.Write("<script language=\"javascript\">alert(\"" + msg + "\");window.open(\"" + uri + "\",\"" + openType + "\",\"\");</script>");
            }
            public static void ShowLocal(string msg, string uri)
            {
                HttpContext.Current.Response.Write("<script language=\"javascript\">alert(\"" + msg + "\");location.href=\"" + uri + "\";</script>");
            }
            public static void ShowBack(string msg)
            {
                HttpContext.Current.Response.Write("<script language=\"javascript\">alert(\"" + msg + "\");history.back(-1);</script>");
            }
        #endregion
       
        /// <summary>
        /// 获得一个域名的顶级 ，如果不是，则返回""
        /// </summary>
        /// <param name="domainStr"></param>
        /// <returns></returns>
        public static string GetTopDomain(string domainStr)
        {
            if ("localhost".Equals(domainStr))
            {
                return "localhost";
            }
            string lastDomain = "";
            string[] domtxt = { ".com.cn", ".net.cn", ".org.cn", ".gov.cn", ".com", ".cn", ".org", ".net", ".info" };
            string domainStrTemp = domainStr;
            for (int i = 0; i < domtxt.Length; i++)
            {
                domainStrTemp = domainStrTemp.Replace(domtxt[i], "");
            }
            string suffix = domainStr.Replace(domainStrTemp, "");
            string[] domainArr = domainStrTemp.Split('.');
            int numCount = domainArr.Length;
            switch (numCount)
            {
                case 1:
                    if (domainArr[0] != "")
                    {
                        lastDomain = domainArr[0] + suffix;
                    }
                    break;
                case 2:
                    if (domainArr[1] != "")
                    {
                        lastDomain = domainArr[1] + suffix;
                    }
                    break;
                default:
                    break;
            }

            if (lastDomain.IndexOf(":") != -1)
            {
                lastDomain = lastDomain.Substring(0, lastDomain.IndexOf(":"));
            }
            return lastDomain;
        }

        #region ip操作
        public static string GetIp()
        {
            string userIP = "";
            //可以透过代理服务器
            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                userIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            if (userIP == null || userIP == "")
            {
                //没有代理服务器,如果有代理服务器获取的是代理服务器的IP
                userIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return userIP;
        }
        public static string GetRealIP()
        {
            string ip;
            try
            {
                HttpRequest request = HttpContext.Current.Request;

                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
                }
                else
                {
                    ip = request.UserHostAddress;
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return ip;
        }

        public static string GetViaIP()
        {
            string viaIp = null;

            try
            {
                HttpRequest request = HttpContext.Current.Request;

                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    viaIp = request.UserHostAddress;
                }

            }
            catch (Exception e)
            {

                throw e;
            }

            return viaIp;
        }
        /// <summary>
        /// IP转长整型
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public static long Ip2Long(string ipAddress)
        {
            System.Net.IPAddress ip = System.Net.IPAddress.Parse(ipAddress);
            int x = 3;
            long o = 0;

            foreach (byte f in ip.GetAddressBytes())
            {
                o += (long)f << 8 * x--;
            }

            return o;
        }
        /// <summary>
        /// 判定是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIp(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        /// <summary>
        /// 隐藏IP
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string HideIp(string ip)
        {

            if (IsIp(ip))
            {
                string[] ips = ip.Split('.');
                return string.Format("{0}.{1}.*.{2}", ips[0], ips[1], ips[3]);
            }


            if (string.IsNullOrEmpty(ip))
            {
                return "UFO";
            }

            int cutIndex;

            cutIndex = ip.IndexOf(" ");


            if (cutIndex > 0)
            {
                ip = ip.Substring(0, cutIndex + 1);
            }

            cutIndex = ip.IndexOf("局域网");

            if (cutIndex >= 0)
            {
                return "UFO";
            }

            cutIndex = ip.IndexOf("本机地址");

            if (cutIndex >= 0)
            {
                return "UFO";
            }

            cutIndex = ip.IndexOf("县");
            if (cutIndex > 0)
            {
                return ip.Substring(0, cutIndex + 1);

            }

            cutIndex = ip.IndexOf("区");
            if (cutIndex > 0)
            {
                return ip.Substring(0, cutIndex + 1);
            }

            cutIndex = ip.IndexOf("市");
            if (cutIndex > 0)
            {
                return ip.Substring(0, cutIndex + 1);
            }

            cutIndex = ip.IndexOf("省");
            if (cutIndex > 0)
            {
                return ip.Substring(0, cutIndex + 1);
            }

            cutIndex = ip.IndexOf("大学");
            if (cutIndex > 0)
            {
                return ip.Substring(0, cutIndex + 1);
            }
            return ip;
        }
        #endregion
        /// <summary>
        /// 以指定的ContentType输出指定文件文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="filename">输出的文件名</param>
        /// <param name="filetype">将文件输出时设置的ContentType</param>
        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;

            // 缓冲区为10k
            byte[] buffer = new Byte[10000];
            // 文件长度
            int length;
            // 需要读的数据长度
            long dataToRead;

            try
            {
                // 打开文件
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                // 需要读的数据长度
                dataToRead = iStream.Length;

                HttpContext.Current.Response.ContentType = filetype;
                if (HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].IndexOf("MSIE") > -1)
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utilz.UrlEncode(filename.Trim()).Replace("+", " "));
                else
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename.Trim());

                while (dataToRead > 0)
                {
                    // 检查客户端是否还处于连接状态
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        // 如果不再连接则跳出死循环
                        dataToRead = -1;
                    }
                }
            }
            catch (Exceptionz ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    // 关闭文件
                    iStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }

    }
}
